package com.ftg.learn.chapter06.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author kangjx
 * @createTime 2022/11/8
 */
@Configuration
public class MyConfig {


    @Bean
    public JdbcTemplate initJdbcTemplate(){
        MysqlDataSource mysql = new MysqlDataSource();
        mysql.setURL("jdbc:mysql://localhost:3306/ad");
        mysql.setUser("root");
        //密码是对的 .... 过期时间 ,它过期 一直重新连接 mysql
        mysql.setPassword("Love0913@kjx");
        JdbcTemplate j = new JdbcTemplate(mysql);
        return j;
    }

    @Bean
    public FastJsonHttpMessageConverter configureMessageConverters() {
        //new FastJsonHttpMessageConverter instance converter
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //new FastJsonConfig instacne config
        FastJsonConfig config = new FastJsonConfig();
        //
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        //
        converter.setFastJsonConfig(config);
        //
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        //
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题，相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        //
        converter.setSupportedMediaTypes(mediaTypeList);
        //
        return converter;
    }

}
